package com.nbatch.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileUploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest req){
        //String realPath = req.getSession().getServletContext().getRealPath("/static/uploadFile/");
        String realPath = "/usr/local/code/nbatch/src/main/resources/static/uploadFile/";

        //文件存放的日期文件夹
        String format = sdf.format(new Date());
        System.out.println(realPath+format);
        File folder = new File(realPath+format);
        if(!folder.isDirectory()){
            folder.mkdirs();
        }
        //获取上传的文件名
        String oldName = uploadFile.getOriginalFilename();
        //获取后缀名
        String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());
        try{
            uploadFile.transferTo(new File(folder,newName));
            //文件路径
            String filePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/uploadFile/"+format+newName;
            return filePath;

        }catch (IOException e){
            e.printStackTrace();
        }
        return "上传失败";
    }

}
